package com.zb.springcloud.lb.impl;

import com.zb.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLb implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);
public final int getAndIncrement(List<ServiceInstance> serviceInstances){
    for (;;){
        int current;
        int next;
       current = this.atomicInteger.get();
//       next = current >= 214748367 ? 0 : current + 1;
//       if (this.atomicInteger.compareAndSet(current, next)){
//           System.out.println("*****第几次访问， 次数next:  " + next);
//           return next;
//       };
        next = (current + 1) % serviceInstances.size();
        if (this.atomicInteger.compareAndSet(current, next)){
           System.out.println("*****第几次访问， 次数next:  " + next);
           return next;
       };
    }
}

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
   // int size = getAndIncrement() % serviceInstances.size();
     //   return serviceInstances.get(size);
        return serviceInstances.get(getAndIncrement(serviceInstances));
    }
}
